package org.nf.trading.controller.app.message;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.nf.trading.controller.BaseController;
import org.nf.trading.dto.ChatMessageDTO;
import org.nf.trading.dto.CommentMessageDTO;
import org.nf.trading.dto.MessageDTO;
import org.nf.trading.entity.Message;
import org.nf.trading.service.app.message.MessageService;
import org.nf.trading.vo.ResultVO;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/message")
@Slf4j
@CrossOrigin
public class MessageController extends BaseController {
    private final MessageService messageService;

    @PostMapping("/chat")
    public ResultVO chatSendMessage(@RequestBody ChatMessageDTO chatMessageDTO){
        messageService.chatSender(chatMessageDTO);
        System.out.println(chatMessageDTO);
        return success("发送成功");
    }

    /**
     * 通过消息的id查询发送者和接收者
     * @param messageId
     * @return
     */
    @GetMapping("/{messageId}")
    public ResultVO listMessageUser(@PathVariable("messageId") Integer messageId){
        CommentMessageDTO commentMessageDTO = messageService.messageUser(messageId);
        return success(commentMessageDTO);
    }


    /**
     * 通过收件人id查询全部消息
     * @param receiverId
     * @return
     */
    @GetMapping("/receiverId/{receiverId}")
    public ResultVO listMessageByReceiverId(@PathVariable("receiverId") Integer receiverId){
        List<Message> messageList = messageService.listMessageByReceiverId(receiverId);
        return success(messageList);
    }

    @PostMapping("/send")
    private ResultVO sendMsg(@RequestBody Message message){
        log.info("消息数据：{}",message);
        List list = new ArrayList<>();
        list.add(message.getMessageContent());
        try {
            message.setMessageContent(new ObjectMapper().writeValueAsString(list));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        boolean insert = messageService.insert(message);
        return success(200,"发送成功",insert);
    }
    @PostMapping("/sendCommentMsg")
    private ResultVO sendCommentMsg(@RequestBody MessageDTO messageDTO){
        messageService.publish(messageDTO);
        return success(200,"发送成功",true);
    }

    /**
     * 通过用户id查询全部消息
     * @param userId
     * @return
     */
    @GetMapping("/userId/{userId}")
    public ResultVO selectByUserId(@PathVariable("userId") Integer userId){
        List<Message> messages = messageService.selectByUserId(userId);
        return success(messages);
    }
}
